import { minify } from "html-minifier-terser";
import PostCSS from "postcss";
import cssnano from "cssnano";
import { format } from "prettier/standalone";
import htmlParser from "prettier/plugins/html";
import cssParser from "prettier/plugins/postcss";
import babel from "prettier/plugins/babel";
import estree from "prettier/plugins/estree";
import meriyah from "prettier/plugins/meriyah";
import acorn from "prettier/plugins/acorn";

const pcss = PostCSS([
  cssnano({
    preset: "default",
  }),
]);

export const minifyCSS = (code: string) =>
  pcss.process(code, { from: "inline" }).then((result) => result.css);

export const htmlMinifyOptions = {
  collapseBooleanAttributes: true,
  collapseInlineTagWhitespace: true,
  collapseWhitespace: true,
  decodeEntities: true,
  html5: true,
  minifyCSS,
  minifyJS: true,
  preventAttributesEscaping: true,
  processConditionalComments: true,
  removeAttributeQuotes: true,
  removeEmptyAttributes: true,
  removeOptionalTags: true,
  removeRedundantAttributes: true,
  removeScriptTypeAttributes: true,
  removeStyleLinkTypeAttributes: true,
  removeTagWhitespace: true,
  sortAttributes: true,
  sortClassName: true,
  trimCustomFragments: true,
};

export const minifyHtml = (code: string) =>
  minify(code, htmlMinifyOptions).then((result) =>
    result.replace(/<!--/g, "\n<!--").replace(/-->/g, "-->\n"),
  );

export const pretty = (code: string, lang: string) =>
  format(code, {
    parser: lang,
    plugins: [htmlParser, cssParser, estree, meriyah, acorn, babel],
    bracketSameLine: true,
  });
